#include "Poller/EventPoller.h"
#include <gtest/gtest.h>
// #include "EventPoller.h"
#include <thread>
#include <atomic>

using namespace toolkit;

// 测试 EventPollerPool 单例获取
TEST(EventPollerPoolTest, Instance) {
    EventPollerPool &pool = EventPollerPool::Instance();
    EXPECT_NE(&pool, nullptr);
}

// 测试设置 EventPollerPool 池大小
TEST(EventPollerPoolTest, SetPoolSize) {
    size_t poolSize = 2;
    EventPollerPool::setPoolSize(poolSize);
    EventPollerPool &pool = EventPollerPool::Instance();
    auto firstPoller = pool.getFirstPoller();
    EXPECT_NE(firstPoller, nullptr);
}

// 测试设置 CPU 亲和性
TEST(EventPollerPoolTest, EnableCpuAffinity) {
    EventPollerPool::enableCpuAffinity(true);
    // 由于无法直接验证 CPU 亲和性设置，这里仅验证接口调用不抛出异常
    EXPECT_NO_THROW(EventPollerPool::Instance());
}

// 测试获取第一个 EventPoller 实例
TEST(EventPollerPoolTest, GetFirstPoller) {
    EventPollerPool &pool = EventPollerPool::Instance();
    auto firstPoller = pool.getFirstPoller();
    EXPECT_NE(firstPoller, nullptr);
}

// 测试根据负载获取轻负载的 EventPoller 实例
TEST(EventPollerPoolTest, GetPoller) {
    EventPollerPool &pool = EventPollerPool::Instance();
    auto poller = pool.getPoller(true);
    EXPECT_NE(poller, nullptr);
}

// 测试设置是否优先返回当前线程
TEST(EventPollerPoolTest, PreferCurrentThread) {
    EventPollerPool &pool = EventPollerPool::Instance();
    pool.preferCurrentThread(false);
    auto poller = pool.getPoller();
    EXPECT_NE(poller, nullptr);
    pool.preferCurrentThread(true);
}

// 测试在多线程环境下获取 EventPoller 实例
TEST(EventPollerPoolTest, GetPollerMultiThread) {
    EventPollerPool &pool = EventPollerPool::Instance();
    std::atomic<bool> testPassed{true};

    auto threadFunc = [&pool, &testPassed]() {
        auto poller = pool.getPoller(true);
        if (poller == nullptr) {
            testPassed = false;
        }
    };

    std::thread t1(threadFunc);
    std::thread t2(threadFunc);

    t1.join();
    t2.join();

    EXPECT_TRUE(testPassed);
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}